﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using WindowsGame.Enums;

namespace WindowsGame.Input
{
	public class PhoneInputFactory : IInputFactory
	{
		private Vector2 touchPosition;
		private Boolean tap, hold, doubleTap, horizontalDrag, verticalDrag;

		public PhoneInputFactory()
		{
			TouchPanel.EnabledGestures = GestureType.Tap | GestureType.DoubleTap | GestureType.Hold | GestureType.HorizontalDrag | GestureType.VerticalDrag;
		}
		
		public void Update(GameTime gameTime)
		{
			touchPosition = GetTouchPosition();

			tap = hold = doubleTap = horizontalDrag = verticalDrag = false;
			if (!TouchPanel.IsGestureAvailable)
			{
				return;
			}

			GestureSample gesture = TouchPanel.ReadGesture();
			tap				= gesture.GestureType == GestureType.Tap;
			hold			= gesture.GestureType == GestureType.Hold;
			doubleTap		= gesture.GestureType == GestureType.DoubleTap;
			horizontalDrag	= gesture.GestureType == GestureType.HorizontalDrag;
			verticalDrag	= gesture.GestureType == GestureType.VerticalDrag;
		}

		public Boolean Escape()
		{
			return GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed;
		}
		public Boolean Load()
		{
			return false;
		}
		public Direction Rotate()
		{
			if (touchPosition == Vector2.Zero || touchPosition.Y < 240)
			{
				return Direction.None;
			}

			return touchPosition.X < 400 ? Direction.Left : Direction.Right;
		}
		public Boolean Thrust()
		{
			if (touchPosition == Vector2.Zero || touchPosition.Y >= 240)
			{
				return false;
			}

			return touchPosition.X >= 400;
		}
		public Boolean Brake()
		{
			if (touchPosition == Vector2.Zero || touchPosition.Y >= 240)
			{
				return false;
			}

			return touchPosition.X < 400;
		}
		public Boolean Shoot()
		{
			return verticalDrag;
		}
		public Boolean Next()
		{
			return doubleTap;
		}
		public Boolean Prev()
		{
			return horizontalDrag;
		}
		private static Vector2 GetTouchPosition()
		{
			Vector2 touchPosition = Vector2.Zero;

			TouchCollection touchCollection = TouchPanel.GetState();
			if (touchCollection.Count > 0)
			{
				TouchLocation location = touchCollection[0];
				touchPosition = location.Position;
			}

			return touchPosition;
		}
	}
}